/*******************************************************************************
 * Copyright (c) Jonathan Buck - jonbuck16@gmail.com
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    jonbuck16@gmail.com - initial API and implementation
 *******************************************************************************/
package net.jonbuck.tassoo.ui.wizard;

import java.text.ParseException;

import net.jonbuck.tassoo.model.Category;
import net.jonbuck.tassoo.model.Container;
import net.jonbuck.tassoo.model.Priority;
import net.jonbuck.tassoo.model.Status;
import net.jonbuck.tassoo.model.Task;
import net.jonbuck.tassoo.model.TassooFactory;
import net.jonbuck.tassoo.model.TassooPackage;
import net.jonbuck.tassoo.model.Type;
import net.jonbuck.tassoo.persistence.dao.TassooDao;
import net.jonbuck.tassoo.persistence.dao.TassooDaoImpl;
import net.jonbuck.tassoo.persistence.dao.util.TassooDaoHelperUtil;
import net.jonbuck.tassoo.persistence.exception.TassooCreationException;
import net.jonbuck.tassoo.persistence.exception.TassooQueryException;
import net.jonbuck.tassoo.ui.wizard.model.NewTaskModel;
import net.jonbuck.tassoo.ui.wizard.page.TaskDetailsPage;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

/**
 * 
 * 
 * @since 1.0.0
 */
public class NewTaskWizard extends Wizard implements INewWizard {

	/** ...TODO... */
	private boolean isSubTask;

	/** ...TODO... */
	private NewTaskModel newTaskModel;

	/** ...TODO... */
	private IStructuredSelection selection;

	/** Tassoo Data Access Object. */
	private TassooDao tassooDao = TassooDaoImpl.getInstance();

	/** ...TODO... */
	private TassooFactory tassooFactory;

	/** ...TODO... */
	private TassooPackage tassooPackage;

	/**
	 * 
	 */
	public NewTaskWizard() {
		this(false);
	}

	/**
	 * 
	 * @param isSubTask
	 */
	public NewTaskWizard(boolean isSubTask) {
		super();
		this.isSubTask = isSubTask;
	}

	/**
	 * 
	 */
	public void addPages() {
		addPage(new TaskDetailsPage(TaskDetailsPage.PAGE_NAME, newTaskModel));
	}

	/**
	 * 
	 * @param selection
	 * @return
	 */
	private String calculateContainer(IStructuredSelection selection) {
		String returnValue = StringUtils.EMPTY;
		if (selection != null) {
			Object selectedObject = selection.getFirstElement();
			Container parentContainer = null;
			if (selectedObject instanceof Container) {
				parentContainer = (Container) selectedObject;
			}
			if (selectedObject instanceof Task) {
				Task selectedTask = (Task) selectedObject;
				parentContainer = selectedTask.getContainer();

			}
			if (parentContainer != null) {
				returnValue = parentContainer.getContainerName();
			}
		}
		return returnValue;
	}

	/**
	 * <p>
	 * <b>Creates an empty Task Model object using the default values from the
	 * task store.</b>
	 * </p>
	 * 
	 * @return a <code>NewTaskModel</code> object containing the default values.
	 */
	private void createNewTaskModel() {
		newTaskModel = new NewTaskModel();
		if (tassooDao.isLoaded()) {
			if (isSubTask && this.selection != null) {
				Task currentlySelectedTask = (Task) selection.getFirstElement();
				newTaskModel.setCategory(currentlySelectedTask.getCategory().getValue());
				newTaskModel.setContainer(currentlySelectedTask.getContainer().getContainerName());
				newTaskModel.setParentTask(currentlySelectedTask.getTaskName());
				newTaskModel.setPriority(currentlySelectedTask.getPriority().getValue());
				newTaskModel.setStatus(TassooDaoHelperUtil.getDefaultStatus(tassooDao));
				newTaskModel.setSubTask(true);
				newTaskModel.setType(currentlySelectedTask.getType().getValue());
			} else {
				newTaskModel.setCategory(TassooDaoHelperUtil.getDefaultCategory(tassooDao));
				newTaskModel.setContainer(calculateContainer(selection));
				newTaskModel.setPriority(TassooDaoHelperUtil.getDefaultPriority(tassooDao));
				newTaskModel.setStatus(TassooDaoHelperUtil.getDefaultStatus(tassooDao));
				newTaskModel.setType(TassooDaoHelperUtil.getDefaultType(tassooDao));
			}
		}
	}

	/**
	 * 
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
		tassooPackage = TassooPackage.eINSTANCE;
		tassooFactory = tassooPackage.getTassooFactory();
		createNewTaskModel();
	}

	/**
	 * 
	 */
	public boolean performFinish() {
		try {
			Task newTask = tassooFactory.createTask();

			newTask.setAttachmentContainer(tassooFactory.createAttachmentContainer());

			newTask.setTaskName(newTaskModel.getTaskName());
			newTask.setTaskSummary(newTaskModel.getTaskSummary());

			Container parentContainer = TassooDaoHelperUtil.getContainerByValue(tassooDao, newTaskModel.getContainer());
			newTask.setContainer(parentContainer);

			Category category = TassooDaoHelperUtil.getCategoryByValue(tassooDao, newTaskModel.getCategory());
			newTask.setCategory(category);

			Priority priority = TassooDaoHelperUtil.getPriorityByValue(tassooDao, newTaskModel.getPriority());
			newTask.setPriority(priority);

			Status status = TassooDaoHelperUtil.getStatusByValue(tassooDao, newTaskModel.getStatus());
			newTask.setStatus(status);

			Type type = TassooDaoHelperUtil.getTypeByValue(tassooDao, newTaskModel.getType());
			newTask.setType(type);

			try {
				if (StringUtils.isNotBlank(newTaskModel.getStartDate())) {
					newTask.setStartDate(DateUtils.parseDate(newTaskModel.getStartDate(),
							new String[] { "dd.MM.yyyy hh:mm:ss.SSS Z" }));
				}
				if (StringUtils.isNotBlank(newTaskModel.getDueDate())) {
					newTask.setDueDate(DateUtils.parseDate(newTaskModel.getDueDate(),
							new String[] { "dd.MM.yyyy hh:mm:ss.SSS Z" }));
				}
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			newTask.setEstimatedTime(newTaskModel.getEstimatedTime());

			newTask.setId(TassooDaoHelperUtil.getNextTaskId(tassooDao, parentContainer));

			if (newTaskModel.isSubTask()) {
				tassooDao.createNewTask(newTask,
						TassooDaoHelperUtil.getTaskByValue(tassooDao, parentContainer, newTaskModel.getParentTask()));
			} else {
				tassooDao.createNewTask(newTask, parentContainer);
			}

			return true;

		} catch (TassooCreationException tce) {
			// TODO Handle using proper exception handling techniques
		} catch (TassooQueryException e) {
			// TODO Handle using proper exception handling techniques
			e.printStackTrace();
		}
		return false;
	}

}
